package com.xindaoapp.happypet.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.bean.IndexTag;
import com.xindaoapp.happypet.view.KeywordsFlow;

public class SearchActivity extends UMBaseActivity implements OnClickListener {
    private ArrayList<IndexTag> list;
    private ListView lv_search;
    private TextView tv_cancle;
    private AutoCompleteTextView act_search;
    private TextView clear_history;
    private KeywordsFlow keywordsFlow;
    private SharedPreferences sp;
    private String history = null;
    private MySearchAdapter mAdapter;
    private String mHistory;
    private ImageView delete;
    private ImageView back;

    private String[] num;
    private boolean isHistory = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = getSharedPreferences(SearchActivity.class.getSimpleName(), MODE_PRIVATE);
        setContentView(R.layout.activity_search);

        initView();
        initData();
    }

    private void initView() {
        list = (ArrayList<IndexTag>) getIntent().getSerializableExtra("list");
        lv_search = (ListView) findViewById(R.id.lv_search);
        clear_history = (TextView) findViewById(R.id.tv_clear_history);
        act_search = (AutoCompleteTextView) findViewById(R.id.searchview);

        tv_cancle = (TextView) findViewById(R.id.tv_search_cancle);
        delete = (ImageView) findViewById(R.id.delete);
        back = (ImageView) findViewById(R.id.back);

        clear_history.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);
        delete.setOnClickListener(this);
        back.setOnClickListener(this);

        keywordsFlow = (KeywordsFlow) findViewById(R.id.keywords_flow);
        keywordsFlow.setDuration(800l);
        keywordsFlow.setOnItemClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof TextView) {
                    String text = ((TextView) v).getText().toString();
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("str", text);
                    startActivity(intent);
                }
            }
        });

        feedKeywordsFlow(keywordsFlow, list);
        keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_clear_history:// 清除历史记录
                act_search.setText("");
                clear_history.setVisibility(View.GONE);
                lv_search.setVisibility(View.GONE);
                Editor editor = sp.edit();
                editor.putString("history", "").commit();
                break;
            case R.id.delete:
                act_search.setText("");
                delete.setVisibility(View.GONE);
                isHistory = false;
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    private void initData() {
        mAdapter = new MySearchAdapter();
        history = sp.getString("history", "");
        num = history.split("&&");
        if (!TextUtils.isEmpty(history)) {
            lv_search.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
        } else {
            lv_search.setVisibility(View.GONE);
            clear_history.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
        }

        act_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (act_search.getText().toString().length() > 0) {
                    tv_cancle.setVisibility(View.VISIBLE);
                    delete.setVisibility(View.VISIBLE);
                } else {
                    tv_cancle.setVisibility(View.GONE);
                    delete.setVisibility(View.GONE);
                    return;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (act_search.getText().toString().length() > 0) {
                    lv_search.setVisibility(View.VISIBLE);
                    clear_history.setVisibility(View.VISIBLE);
                }
            }
        });

        act_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isHistory = true;
            }
        });

        tv_cancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String str = act_search.getText().toString().toString().trim();
                if (TextUtils.isEmpty(str)) {
                    Toast.makeText(SearchActivity.this, "搜索内容不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }

                String history1 = sp.getString("history", "");
                if (!history1.contains(str)) {
                    mHistory = history1 + str + "&&";
                } else {
                    mHistory = history1;
                }

                num = mHistory.split("&&");

                lv_search.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();

                if (isHistory) {
                    Editor editor = sp.edit();
                    editor.putString("history", mHistory).commit();
                }
                Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                intent.putExtra("str", str);
                startActivity(intent);
            }
        });
    }

    private class MySearchAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return num.length;
        }

        @Override
        public Object getItem(int position) {
            return num[position];
        }

        @Override
        public long getItemId(int position) {
            return num.length;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = View.inflate(SearchActivity.this, R.layout.list_item_search, null);
            TextView tv = (TextView) view.findViewById(R.id.header);
            tv.setText(num[position]);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    act_search.setText(num[position]);
                    isHistory = false;
                }
            });
            return view;
        }

    }

    private static void feedKeywordsFlow(KeywordsFlow keywordsFlow, ArrayList<IndexTag> list) {
        for (int i = 0; i < list.size(); i++) {
            keywordsFlow.feedKeyword(list.get(i).getName());
        }
    }
}
